package com.origin.baselibrary.devices

import android.content.Context
import android.os.Build
import android.telephony.TelephonyManager
import android.util.Log
import androidx.fragment.app.FragmentActivity
import com.origin.utils.permissions.OnPermissionPageCallback
import com.origin.utils.permissions.PermissionsUtils
import java.lang.reflect.Method
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine


object DevicesUtils {


    private suspend fun  _getImei(activity: FragmentActivity,telephonyManager:TelephonyManager):String{
         return suspendCoroutine { continuation ->

             PermissionsUtils.requestPermissions(activity, android.Manifest.permission.READ_PHONE_STATE,onPermissionPageCallback = object : OnPermissionPageCallback {
                 override fun onGranted(permissions: MutableList<String>?) {
                     // Android 6.0 - Android 8.0
                     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
                         continuation.resume(telephonyManager.getDeviceId())
                     }else

                     // Android 8.0 - Android 10.0
                     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && Build.VERSION.SDK_INT <= Build.VERSION_CODES.Q) {

                         val method: Method = telephonyManager.javaClass.getMethod(
                             "getImei",
                             Int::class.javaPrimitiveType
                         )
                         // 如果手机是双卡的是有两个imei值的
                         val imei1 = method.invoke(telephonyManager, 0) as String
                         val imei2 = method.invoke(telephonyManager, 1) as String
                         continuation.resume(telephonyManager.getImei())
                     }
                 }

                 override fun onDenied(permissions: MutableList<String>?) {
                     continuation.resumeWithException(Throwable())
                 }
             })

        }
    }

    suspend fun  getImei(activity: FragmentActivity) :String{
        if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.Q) {
            return ""
        }
        try {
            var telephonyManager =
                activity.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager;
            // Android 6以下
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
               return telephonyManager.getDeviceId();
            }
            return  _getImei(activity,telephonyManager)




        } catch (e: Exception) {

        }

        return ""

    }
}